import { getDbClient } from "./db.ts";

// 读取SQL文件内容
async function readSqlFile(filePath: string): Promise<string> {
  try {
    const fileContent = await Deno.readTextFile(filePath);
    return fileContent;
  } catch (error) {
    console.error(`Error reading SQL file ${filePath}:`, error);
    return "";
  }
}

// 执行SQL语句
async function executeSql(sql: string): Promise<boolean> {
  if (!sql) return false;
  
  const client = await getDbClient();
  try {
    // 分割SQL语句（简单处理，假设语句以分号结尾）
    const statements = sql
      .split(';')
      .map(s => s.trim())
      .filter(s => s.length > 0);
    
    for (const statement of statements) {
      try {
        await client.execute(statement + ';');
        console.log("SQL执行成功:", statement.substring(0, 50) + "...");
      } catch (error) {
        console.error("SQL执行错误:", error);
        console.error("有问题的SQL:", statement);
        return false;
      }
    }
    return true;
  } catch (error) {
    console.error("数据库连接或执行错误:", error);
    return false;
  } finally {
    await client.close();
  }
}

// 主函数
async function initializeDatabase() {
  console.log("开始初始化数据库...");
  
  // 用户表
  const usersSql = await readSqlFile("./utils/create_users_table.sql");
  const usersResult = await executeSql(usersSql);
  console.log("用户表初始化:", usersResult ? "成功" : "失败");
  
  // 文章表
  const postsSql = await readSqlFile("./utils/create_posts_table.sql");
  const postsResult = await executeSql(postsSql);
  console.log("文章表初始化:", postsResult ? "成功" : "失败");
  
  console.log("数据库初始化完成!");
}

// 执行初始化
if (import.meta.main) {
  await initializeDatabase();
} 